from ultralytics import YOLO
import time

import requests
from requests.auth import HTTPDigestAuth
from PIL import Image
from io import BytesIO

import subprocess
result = subprocess.run(['gpio', 'mode', '13', 'out'], capture_output=True, text=True)
result = subprocess.run(['gpio', 'write', '13', '0'], capture_output=True, text=True)
# 请求头
headers = {
    'Content-Type': 'application/json',
    'User-Agent': 'curl/4.7.1',
    'Cache-Control': 'no-cache',
    'Postman-Token': 'cfdf0937-f7a5-4b79-8c39-42eb232d4c0b',
}
username = 'admin'
password = '123456'  # 密码通常需要填写，但在此示例中未提供
camera_ip = "192.168.50.187"

conf_num = 0.4
ratio_num = 1.3
play_sound = False                             

def http_post_light_capture():
    
    url = 'http://' + camera_ip + '/digest/CaptureV2'
    data = {
        "Type": 1,
        "Ch": 1,
        "Dev": 1,
        "Data": {
            "DataType": 0,
            "StreamNo": 0
        }
    }

    response = requests.post(url, json=data, headers=headers, auth=HTTPDigestAuth(username, password))

    image_bytes = BytesIO(response.content)

    # 使用Pillow来打开图像
    image = Image.open(image_bytes)

    # 保存图像
    print("image saved")
    image.save(r'/home/orangepi/Desktop/orangepi/image.jpg')

def http_post_light_turn_on():

    url = 'http://' + camera_ip + '/digest/frmIotLightCfg'

    data = {
        "Type": 1,
        "Ch": 1,
        "Dev": 1,
        "Data": {
            "Mode": 'Warm',
            "Control": 1,
            "LightOnTime": 2,
            "Brightness": 100
        }
    }
    response = requests.post(url, json=data, headers=headers, auth=HTTPDigestAuth(username, password))

def http_post_light_turn_off():
    url = 'http://' + camera_ip + '/digest/frmIotLightCfg'

    data = {
        "Type": 1,
        "Ch": 1,
        "Dev": 1,
        "Data": {
            "Mode": 'Ir',
            "Control": 2,
            "LightOnTime": 2,
            "Brightness": 100
        }
    }
    response = requests.post(url, json=data, headers=headers, auth=HTTPDigestAuth(username, password))

def http_post_laser_turn_on():
    url = 'http://' + camera_ip + '/digest/frmAlarmOut'

    # 请求体
    data = {
        "Type": 1,
        "Ch": 1,
        "Dev": 1,
        "Data": {
            "AlarmCh": 1,
            "AlarmType": 1,
            'SelfDefinedDelay': 5,
            'AlarmOutDelay': 2
        },
    }

    response = requests.post(url, json=data, headers=headers, auth=HTTPDigestAuth(username, password))

def http_post_laser_turn_off():
    url = 'http://' + camera_ip + '/digest/frmAlarmOut'

    # 请求体
    data = {
        "Type": 1,
        "Ch": 1,
        "Dev": 1,
        "Data": {
            "AlarmCh": 1,
            "AlarmType": 0,
            'SelfDefinedDelay': 5,
            'AlarmOutDelay': 2
        },
    }

    response = requests.post(url, json=data, headers=headers, auth=HTTPDigestAuth(username, password))

def http_post_sound_upload(path):

    import base64

    def encode_audio_to_base64(audio_file_path):
        """
        Encodes a WAV audio file to a Base64 string.

        Args:
            audio_file_path (str): The path to the WAV audio file.

        Returns:
            str: The Base64 encoded string of the audio file, or None if an error occurs.
        """
        try:
            with open(audio_file_path, "rb") as audio_file:
                encoded_string = base64.b64encode(audio_file.read()).decode('utf-8')
            return encoded_string
        except FileNotFoundError:
            print(f"Error: File not found at {audio_file_path}")
            return None
        except Exception as e:
            print(f"An error occurred: {e}")
            return None

    # Example usage:
    file_path = path  # Replace with the actual path to your WAV file
    base64_data = encode_audio_to_base64(file_path)

    # 请求的URL
    url = 'http://192.168.50.187/digest/frmSetCustomAudio'

    # 请求体
    data = {
        "Type": 1,
        "Ch": 1,
        "Data": {
                "DetectType": 9,
                "AudioDataType": 2,
                "AudioData": base64_data
        }
    }

    response = requests.post(url, json=data, headers=headers, auth=HTTPDigestAuth(username, password))

def http_play_sound():
    # 请求的URL
    url = 'http://192.168.50.187/digest/frmAudioSpeech'

    # 请求体
    data = {
        "Type": 1,
        "Dev":1,
        "Ch": 1,
        "Data": {
                "DetectType": 9,
                "AudioSelected": 1
        }
    }

    # 发送请求
    response = requests.post(url, json=data, headers=headers, auth=HTTPDigestAuth(username, password))

model = YOLO("/home/orangepi/Desktop/orangepi/yolo11s.pt")
print("started!!!!")

import threading

class StoppableWorker:
    def __init__(self):
        self._stop_event = threading.Event()

    def run(self):
        print("worker thread running")
        while not self._stop_event.is_set():
            print("Worker:Working...")
            http_post_sound_upload("orangepi/Dog Bark 8000.wav")
            http_play_sound()
            time.sleep(2)
            http_post_sound_upload("orangepi/Get out of here 8000.wav")
            http_play_sound()
            time.sleep(2)
            http_post_sound_upload("orangepi/Hawk Screech 8000.wav")
            http_play_sound()
            time.sleep(2)
        print("Worker: Stopped gracefully!")



    def run_laser(self):
        print("worker thread running")
        while not self._stop_event.is_set():
            print("Worker:Working...")
            http_post_laser_turn_on()
            time.sleep(1)
            http_post_laser_turn_off()
            time.sleep(0.3)
            http_post_light_turn_on()
            time.sleep(0.2)
            http_post_light_turn_off()
            time.sleep(0.5)
        print("Worker: Stopped gracefully!")

    def stop(self):
        self._stop_event.set()

worker_started = False
while(True):
    try:
        # worker = StoppableWorker()
        #worker_laser = StoppableWorker()
        src_path = '/home/orangepi/Desktop/orangepi/image.jpg'
        http_post_light_capture()
        print("after capture")
        play_sound = False                             
        results = model((src_path).strip())
        print("results", results)
        conf = results[0][0].boxes.conf[0].item()
        cls = results[0][0].boxes.cls[0].item()
        # print("??", type(results[0][0]))
        print("conf", conf)
        print("cls", cls)
        heron_detected = False
        for result in results:
            boxes = result.boxes
            for i in range(len(boxes)):
                cls_id = int(boxes.cls[i].item())
                conf = boxes.conf[i].item()
                x, w, w, h = boxes.xywh[i].tolist()
                width = w
                height = h

                if conf >= conf_num and cls == 14 and height/width >= ratio_num:
                    print("blue heron!!")
                    heron_detected = True
                    import subprocess
                    sub_result = subprocess.run(['gpio','write','13','1'],capture_output=True, text=True)
                    if not worker_started:
                        for i in range(5):
                            http_post_light_turn_on()
                            time.sleep(0.3)
                            http_post_light_turn_off()
                            time.sleep(1)
                        print("worker started")
                        if play_sound:
                            worker = StoppableWorker()
                            worker_thread = threading.Thread(target=worker.run)
                            worker_thread.start()
                        worker_laser = StoppableWorker()
                        worker_laser_thread = threading.Thread(target=worker_laser.run_laser)
                        worker_laser_thread.start()
                        worker_started = True
                        print("true branch ends")
                else:
                    if not heron_detected:
                        try:
                            print("else branch starts")
                            sub_result=subprocess.run(['gpio','write','13','0'],capture_output=True,text=True)
                            http_post_light_turn_off()
                            worker_started = False
                            worker.stop()
                            worker_laser.stop()
                            worker_thread.join()
                            worker_laser_thread.join()
                            print("no clear object detected")
                        except:
                            print("no clear object detected exception")
    except Exception as e:
        print(e)
        print("no birds detected exception")
    #time.sleep(2)






